﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections.Specialized;

namespace Vbyte.Extension
{
    public static class DataBindExtension
    {   
        
        /// <summary>
        /// 通过词典数据绑定实例
        /// </summary>
        /// <typeparam name="T">实例类型</typeparam>
        /// <param name="instance">当前实例</param>
        /// <param name="nvObject">键值索引集合</param>
        /// <returns></returns>
        public static T DataBind<T>(this T instance, NameValueCollection nvObject)
        {
            if (instance == null) return default(T);
            Type t = instance.GetType();
            foreach (PropertyInfo pi in t.GetProperties())
            {
                if (nvObject[pi.Name] != null)
                {
                    if (pi.PropertyType != typeof(string))
                    {
                        pi.SetValue(instance, Convert.ChangeType(nvObject[pi.Name], pi.PropertyType), null);
                    }
                    else
                    {
                        pi.SetValue(instance, nvObject[pi.Name], null);
                    }
                }
            }
            return instance;
        }

    }
}
